package com.migraine.service.impl;

import com.migraine.mapper.RelationshipMapper;
import com.migraine.mapper.UsersMapper;
import com.migraine.model.Users;
import com.migraine.service.RelationshipService;
import com.migraine.service.UsersService;
import com.migraine.websocket.WebSocketServer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * 用户好友功能service
 */
@Service
public class RelationshipServiceImpl implements RelationshipService {

    @Autowired
    private RelationshipMapper relationshipMapper;

    @Autowired
    private UsersMapper usersMapper;


    // 插入两者的好友关系 name1和name2分别是两者的id
    @Override
    public boolean insertRelationship(String name1, String name2) {
        Integer ans;
        ans = relationshipMapper.getRelationshipId(name1, name2);
        if (ans == null) {
            relationshipMapper.insertRelationship(name1, name2);
            return true;
        } else return false;// 二者已经是好友，无法添加

    }

    // 删除好友关系
    @Override
    public boolean deleteRelationship(String name1, String name2) {
        Integer ans;
        ans = relationshipMapper.getRelationshipId(name1, name2);
        if (ans != null && ans != -1) {

            relationshipMapper.deleteRelationship(name1, name2);
            return true;

        }
        // 不存在关系，不能删除
        return false;
    }

    // 查询两者关系的Id 如果没有关系则返回-1
    @Override
    public int getid(String name1, String name2) {
        Integer ans;
        ans = relationshipMapper.getRelationshipId(name1, name2);
        if (ans != null && ans != -1) {
            return ans;
        }
        return -1;
    }

    // 返回一个用户的所有好友,没有好友返回一个空list
    @Override
    public List<String> getfriends(String name) {
        List<String> friends = relationshipMapper.getRelationship(name);
        return friends;
    }

    /**
     * 根据用户的uid返回用户的好友列表
     *
     * @param uid 用户的uid
     * @return 好友列表
     */
    @Override
    public List<Users> getFriends(String uid) {

        List<String> uidList = relationshipMapper.getRelationship(uid);
        List<Users> usersList = usersMapper.getAllUsers();
        List<Users> resultList = new ArrayList<>();
        for (String eachId : uidList) {
            for (Users user : usersList) {
                if (eachId.equals(user.getUid())) {
                    user.setPassword(null);
                    resultList.add(user);
                    break;
                }
            }
        }

        return resultList;
    }


}
